<?php

namespace utils;

use think\facade\Request;
use think\facade\Filesystem;

class Upload
{
    public static function getFiles($type = 'original')
    {
        $files = Request::file();

        $result = [];
        foreach ($files as $file) {
            $result[] = Filesystem::disk('public')->putFile($type ,$file);
        }
        return $result;
    }

    public static function getVideo()
    {
        if (Request::isPost()) {
            header("Content-type: text/html; charset=utf-8");
            $UpdType = array('swf', 'flv', 'wav', 'wma', 'wmv', 'mp4', 'rmvb', 'asf', 'mkv', 'mpg', 'mepg', '3gp', 'ogg', 'mov');
            $filename = iconv('utf-8','utf-8',$_POST['filename']);
            $fileTypes = explode(".",$filename);
            $updFileExt = strtolower($fileTypes[count($fileTypes)-1]);
            if(!in_array($updFileExt,$UpdType)) die('此类型不允许上传至服务器！');
            $dir = ROOT."/video_fragment/".'/'.md5($filename);
            $dir_complete_file_dir = ROOT.'/video/'.date('Ym', time()).'/'.date('d', time());
            if(!file_exists($dir)){
                mkdir($dir,0777,true);
            }
            if(!file_exists($dir_complete_file_dir)){
                mkdir($dir_complete_file_dir,0777,true);
            }
            $path = $dir."/".$_POST['blobname'];
            move_uploaded_file($_FILES["file"]["tmp_name"],$path);
            if(isset($_POST['lastone'])){
                $count=$_POST['lastone'];
                $videoPathAll = $dir_complete_file_dir.'/'.$filename;
                $fp = fopen($videoPathAll,"abw");
                for($i=0;$i<=$count;$i++){
                    $handle = fopen($dir."/".$i,"rb");
                    fwrite($fp,fread($handle,filesize($dir."/".$i)));
                    fclose($handle);
                    @unlink($dir."/".$i);//删除文件
                }
                @rmdir($dir);//删除文件夹
                fclose($fp);
//                $imgPathALL = self::VideoImg($videoPathAll);
//                $imgPath = str_replace(ROOT, "", $imgPathALL);
                $videoPath = str_replace(ROOT, "", $videoPathAll);
//                return ['videoPath'=>$videoPath, 'videoImgPath'=>$imgPath];
                return ['videoPath'=>$videoPath];
            }else{
                return false;
            }
        } else {
            return false;
        }
    }

    public static function VideoImg($file){

        $pathParts = pathinfo($file);
        $filename = $pathParts['dirname']."/".$pathParts['filename']."_";

        $times = 8;
        $destFilePath = $filename.$times.".jpg";
        $command = "/usr/bin/ffmpeg -i {$file} -y -f image2 -ss {$times} -vframes 1 -s 640x360 {$destFilePath}";
        exec($command);
        return $destFilePath;
    }

    //删除文件
    public static function unlink($path)
    {
        if (file_exists(ROOT . $path)) {
            return unlink(ROOT. $path);
        }
        return false;
    }
}